package com.ssm.sport.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssm.sport.entity.Banner;
import com.ssm.sport.service.BannerService;
import com.ssm.sport.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * 后台轮播图管理控制器
 */
@Controller
@RequestMapping("/admin/banner")
public class AdminBannerController {

    @Autowired
    private BannerService bannerService;

    /**
     * 重定向到轮播图列表页
     */
    @GetMapping("/")
    public String index() {
        return "redirect:/admin/banner/list";
    }
    
    /**
     * 处理/admin/banners URL，重定向到轮播图列表页
     */
    @GetMapping("")
    public String bannerRoot() {
        return "redirect:/admin/banner/list";
    }
    
    /**
     * 兼容老路径：/admin/banners
     */
    @RequestMapping(value = "/admin/banners", method = RequestMethod.GET)
    public String banners() {
        return "redirect:/admin/banner/list";
    }
    
    /**
     * 轮播图列表页
     */
    @GetMapping("/list")
    public String list(Model model,
                      @RequestParam(defaultValue = "1") Integer pageNum,
                      @RequestParam(defaultValue = "10") Integer pageSize) {
        // 记录请求信息用于调试
        System.out.println("Banner list requested - pageNum: " + pageNum + ", pageSize: " + pageSize);
        
        try {
            Page<Banner> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Banner> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.orderByAsc(Banner::getSortOrder);
            
            Page<Banner> bannerPage = bannerService.page(page, queryWrapper);
            System.out.println("Banner data retrieved - total: " + bannerPage.getTotal() + ", current page records: " + 
                            (bannerPage.getRecords() != null ? bannerPage.getRecords().size() : "null"));
            
            model.addAttribute("banners", bannerPage);
            return "admin/banner_list";
        } catch (Exception e) {
            System.err.println("Error loading banner list: " + e.getMessage());
            e.printStackTrace();
            model.addAttribute("errorMsg", "加载轮播图数据失败");
            return "admin/banner_list";
        }
    }
    
    /**
     * 新增轮播图页面
     */
    @GetMapping("/add")
    public String add() {
        return "admin/banner_add";
    }
    
    /**
     * 编辑轮播图页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        Banner banner = bannerService.getById(id);
        model.addAttribute("banner", banner);
        return "admin/banner_edit";
    }
    
    /**
     * 保存轮播图
     */
    @PostMapping("/save")
    @ResponseBody
    public ResponseVO save(Banner banner, @RequestParam(required = false) MultipartFile imageFile, 
                          HttpServletRequest request) {
        try {
            // 处理图片上传
            if (imageFile != null && !imageFile.isEmpty()) {
                // 创建专门的轮播图目录
                String realPath = request.getSession().getServletContext().getRealPath("/static/images/carousel/");
                File dir = new File(realPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                
                // 生成新文件名
                String originalFilename = imageFile.getOriginalFilename();
                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
                
                // 保存文件
                File targetFile = new File(realPath, newFileName);
                imageFile.transferTo(targetFile);
                
                // 设置图片URL
                banner.setImageUrl("/static/images/carousel/" + newFileName);
            }
            
            // 设置默认状态
            if (banner.getStatus() == null) {
                banner.setStatus(1); // 默认启用
            }
            
            // 设置默认排序
            if (banner.getSortOrder() == null) {
                banner.setSortOrder(0);
            }
            
            // 设置创建时间和更新时间
            Date now = new Date();
            banner.setCreateTime(now);
            banner.setUpdateTime(now);
            
            boolean success = bannerService.save(banner);
            return success ? ResponseVO.success("添加轮播图成功") : ResponseVO.error("添加轮播图失败");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseVO.error("图片上传失败");
        }
    }
    
    /**
     * 更新轮播图
     */
    @PostMapping("/update")
    @ResponseBody
    public ResponseVO update(Banner banner, @RequestParam(required = false) MultipartFile imageFile, 
                           HttpServletRequest request) {
        try {
            // 处理图片上传
            if (imageFile != null && !imageFile.isEmpty()) {
                // 创建专门的轮播图目录
                String realPath = request.getSession().getServletContext().getRealPath("/static/images/carousel/");
                File dir = new File(realPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                
                // 生成新文件名
                String originalFilename = imageFile.getOriginalFilename();
                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
                
                // 保存文件
                File targetFile = new File(realPath, newFileName);
                imageFile.transferTo(targetFile);
                
                // 设置图片URL
                banner.setImageUrl("/static/images/carousel/" + newFileName);
            }
            
            boolean success = bannerService.updateById(banner);
            return success ? ResponseVO.success("更新轮播图成功") : ResponseVO.error("更新轮播图失败");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseVO.error("图片上传失败");
        }
    }
    
    /**
     * 删除轮播图
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public ResponseVO delete(@PathVariable Integer id) {
        boolean success = bannerService.removeById(id);
        return success ? ResponseVO.success("删除轮播图成功") : ResponseVO.error("删除轮播图失败");
    }
    
    /**
     * 修改轮播图状态
     */
    @PostMapping("/status/{id}/{status}")
    @ResponseBody
    public ResponseVO updateStatus(@PathVariable Integer id, @PathVariable Integer status) {
        Banner banner = new Banner();
        banner.setId(id);
        banner.setStatus(status);
        boolean success = bannerService.updateById(banner);
        return success ? ResponseVO.success("修改状态成功") : ResponseVO.error("修改状态失败");
    }
} 